﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ADDataPro
{
    public partial class WaveShow : Form
    {
        string _url;
        string[] _files;
        object obj = new object();
        int _index = 0;
        public WaveShow(string url, int index, string[] files)
        {
            InitializeComponent();
            _url = url;
            _index = index;
            _files = files;
        }

        private void WaveShow_Load(object sender, EventArgs e)
        {
            double flag = 50;
            double t = Math.Round(flag / 31250, 15);
            List<Tuple<double, double, double, double>> data = new List<Tuple<double, double, double, double>>();
            int count = 0;
            int index = 0;
            Task.Run(() =>
            {
                double sum = 0, acsum = 0;
                chartControl1.Series["4号传感器电压值"].Points.Clear();
                chartControl1.Series["左加速度电压值"].Points.Clear();
                chartControl1.Series["4号传感器高程值"].Points.Clear();
                chartControl1.Series["加速度传感器值"].Points.Clear();
                double speed = 0; //速度
                double preSpeed = 0, prevac = 0;//前一个速度
                double totalMoveVal = 0;
                foreach (var file in _files)
                {
                    using (StreamReader sr = new StreamReader(file))
                    {
                        var temp = getList(file, _index);
                        var actemp = getList(file, 14);
                        double acAllAvg = actemp.Average(x => Convert.ToDouble(x));
                        Invoke(new Action(() =>
                        {
                            var enumer = temp.GetEnumerator();
                            var acnumer = actemp.GetEnumerator();

                            while (enumer.MoveNext() && acnumer.MoveNext())
                            {
                                count++;
                                double.TryParse(enumer.Current, out double val);
                                double.TryParse(acnumer.Current, out double ac);
                                sum += val;
                                acsum += ac;
                                if (count % flag == 0)
                                {
                                    //根据加速度算位移
                                    if (index > 0)
                                    {
                                        preSpeed = data[index - 1].Item2;
                                        prevac = data[index - 1].Item4;
                                    }
                                    double sumavg = sum / flag;
                                    double acavg = acsum / flag; //加速度 m/s²
                                    double curhigh = (sumavg * 1000 + 7 - 2304.61157215999) * 0.0591575958353052; //高程值
                                    double curac = Math.Round((acavg * 1000 - 2099.1454) * -0.00413308534821244, 15); //加速度
                                    speed = Math.Round(preSpeed + curac * t, 15);
                                    double moveVal = Math.Round(speed * t + curac * t * t / 2 * 100, 15); // 位移值
                                    totalMoveVal += moveVal;
                                    data.Add(new Tuple<double, double, double, double>(moveVal, speed, totalMoveVal, acavg));

                                    chartControl1.Series["4号传感器电压值"].Points.AddPoint(count, sumavg); //4号传感器电压值
                                    chartControl1.Series["左加速度电压值"].Points.AddPoint(count, acavg);// 加速度传感器电压值

                                    //chartControl1.Series["4号传感器高程值"].Points.AddPoint(count, curhigh / 10); //4号传感器高程值
                                    //chartControl1.Series["加速度传感器值"].Points.AddPoint(count, moveVal);// 加速度传感器位移值
                                    //根据加速度算速度得到初始速度
                                    //chartControl2.Series["S4"].Points.AddPoint(count, Math.Sin(count)); //高程值
                                    //chartControl2.Series["AC1"].Points.AddPoint(count, moveVal);// 加速度传感器位移值

                                    sum = 0;
                                    acsum = 0;
                                    val = 0;
                                    ac = 0;
                                    index++;
                                }
                            }
                        }));
                    }
                }

                //// 生成一个包含直流分量的信号
                //double[] signal = Enumerable.Range(0, 100).Select(x => 1.0 + Math.Sin(x * 0.1)).ToArray();

                //// 计算直流分量
                //double directCurrentComponent = data.Select(x => x.Item3).Average();

                //// 输出结果
                //chartControl2.Series["AC1"].Points.Clear();
                //Invoke(new Action(() =>
                //{
                //    for (int i = 0; i < data.Count; i++)
                //    {
                //        chartControl2.Series["AC1"].Points.AddPoint(i, data[i].Item3- directCurrentComponent);
                //    }
                //}));

                OutPutList(data);
            });
        }


        public static void Mainaaaaa()
        {
            // 假设的位移和加速度数据
            double[] displacement = { 0, 1, 2, 3, 4, 5 }; // 位移曲线
            double[] acceleration = { 0, 0.5, 0.5, 0.5, 0.5, 0.5 }; // 加速度曲线

            // 计算速度曲线
            double[] velocity = CalculateVelocity(displacement);

            // 计算由加速度引起的位移
            double[] accelerationDisplacement = Integrate(acceleration);

            // 补偿位移曲线
            double[] compensatedDisplacement = new double[displacement.Length];
            for (int i = 0; i < displacement.Length; i++)
            {
                compensatedDisplacement[i] = displacement[i] - accelerationDisplacement[i];
            }

            // 输出结果
            Console.WriteLine("原始位移曲线:");
            PrintArray(displacement);
            Console.WriteLine("加速度曲线:");
            PrintArray(acceleration);
            Console.WriteLine("补偿后的位移曲线:");
            PrintArray(compensatedDisplacement);
        }

        // 计算速度曲线（位移的导数）
        private static double[] CalculateVelocity(double[] displacement)
        {
            int length = displacement.Length;
            double[] velocity = new double[length];
            for (int i = 1; i < length - 1; i++)
            {
                velocity[i] = (displacement[i + 1] - displacement[i - 1]) / 2.0; // 简单的中心差分法
            }
            velocity[0] = (displacement[1] - displacement[0]); // 第一个点的速度
            velocity[length - 1] = (displacement[length - 1] - displacement[length - 2]); // 最后一个点的速度
            return velocity;
        }

        // 积分加速度曲线以计算位移
        private static double[] Integrate(double[] acceleration)
        {
            int length = acceleration.Length;
            double[] displacement = new double[length];
            displacement[0] = 0; // 初始位移为0
            for (int i = 1; i < length; i++)
            {
                displacement[i] = displacement[i - 1] + acceleration[i - 1]; // 简单的积分
            }
            return displacement;
        }

        private static void PrintArray(double[] array)
        {
            foreach (var item in array)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
        }

        public IEnumerable<string> getList(string file, int index)
        {
            using (StreamReader sr = new StreamReader(file))
            {
                var str = sr.ReadToEnd();
                var arr = str.Split(',');
                for (int i = 0; i < arr.Length; i++)
                {
                    if (i % 16 == index)
                    {
                        yield return arr[i];
                    }
                }
            }
        }

        void OutPutList(List<Tuple<double, double, double, double>> list)
        {
            var path = $"{_url}\\TestData";
            string logPath = $"{path}\\TestData_{DateTime.Now.Ticks}.txt";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            using (StreamWriter sw = File.AppendText(logPath))
            {
                for (int i = 0; i < list.Count; i++)
                {
                    sw.WriteLine($"{list[i].Item1},{list[i].Item2},{list[i].Item3}");
                }
            }
        }

    }
}
